package com.GLM.Viewer.FirstLogin;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.InputType;
import android.text.SpannableString;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.GLM.Constants.Constant;
import com.GLM.Tools.Utils.ViewsUtil;
import com.GLM.Tools.Utils.JSON.JSONResponse;
import com.GLM.Tools.Utils.JSON.JSONResponse.Status;
import com.GLM.Tools.Utils.JSON.JSONUtil;
import com.GLM.Viewer.R;

public class RegisterFirstViewActivity extends Activity {
	View mRegisterInputField;
	TextView mRegisterInputTextView;
	EditText mRegisterInputEditText;
	Animation mAnimIn;
	Animation mAnimOut;

	Button mStep1Button;
	Button mStep2Button;
	Button mStep3Button;
	InputMethodManager imm;

	HashMap<String, String> registerSecondViewData;
	String mUserName;
	String mPasswordFirst;
	String mPasswordSecond;
	String mNickname;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_register);
		tryRestoreDataFromRegisterSecondView();
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		mRegisterInputField = findViewById(R.id.register_inputfield);
		mRegisterInputField.setVisibility(View.GONE);
		initAnimation();

		mRegisterInputTextView = (TextView) findViewById(R.id.inputfield_title);
		mRegisterInputEditText = (EditText) findViewById(R.id.inputfield_edittext);

		initStep1Button();

		initStep2Button();

		initStep3Button();

		initRegisterInputFieldButton();
	}

	@SuppressWarnings("unchecked")
	private void tryRestoreDataFromRegisterSecondView() {
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			HashMap<String, String> restoreData = (HashMap<String, String>) bundle.get(Constant.REGISTER_DATA);
			if (restoreData != null) {
				mUserName = restoreData.get(Constant.REGISTER_DATA_USERNAME);
				mPasswordSecond = restoreData.get(Constant.REGISTER_DATA_PASSWORD);
				mNickname = restoreData.get(Constant.REGISTER_DATA_NICKNAME);
			}
		}
	}

	private void initStep2Button() {
		mStep2Button = (Button) findViewById(R.id.registerbutton_step2);
		if (mPasswordSecond != null) {
			initStep2ButtonAfterVerified();
		} else {
			initStep2ButtonBeforeVerified();
		}
	}

	private void initStep1Button() {
		mStep1Button = (Button) findViewById(R.id.registerbutton_step1);
		if (mUserName != null) {
			initStep1ButtonAfterVerified(mUserName);
		} else {
			initStep1ButtonBeforeVerified();
		}
	}

	private void initStep3Button() {
		mStep3Button = (Button) findViewById(R.id.registerbutton_step3);
		if (mNickname != null) {
			initStep3ButtonAfterVerified(mNickname);
		} else {
			initStep3ButtonBeforeVerified();
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString(Constant.REGISTER_DATA_USERNAME, mUserName);
		outState.putString(Constant.REGISTER_DATA_PASSWORD, mPasswordSecond);
		outState.putString(Constant.REGISTER_DATA_NICKNAME, mNickname);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mUserName = savedInstanceState.getString(Constant.REGISTER_DATA_USERNAME);
		mPasswordSecond = savedInstanceState.getString(Constant.REGISTER_DATA_PASSWORD);
		mNickname = savedInstanceState.getString(Constant.REGISTER_DATA_NICKNAME);
	}

	private void initRegisterInputFieldButton() {
		Button inputCancelButton = (Button) findViewById(R.id.inputfield_cancelbutton);
		inputCancelButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				String step = (String) mRegisterInputTextView.getTag();
				if ("step2_first".equals(step)) {
					mRegisterInputTextView.setTag("step2_cancel");
				}
				hideRegisterInputField();
			}
		});

		Button inputOkButton = (Button) findViewById(R.id.inputfield_okbutton);
		inputOkButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				handleRegisterInputFieldOkButtenEvent();

			}
		});
	}

	private void initAnimation() {
		mAnimIn = AnimationUtils.loadAnimation(this, R.anim.anim_register_in);
		mAnimOut = AnimationUtils.loadAnimation(this, R.anim.anim_register_out);
		mAnimOut.setAnimationListener(new AnimationListener() {

			public void onAnimationStart(Animation animation) {

			}

			public void onAnimationRepeat(Animation animation) {

			}

			public void onAnimationEnd(Animation animation) {
				String step = (String) mRegisterInputTextView.getTag();
				if ("step2_first".equals(step)) {
					mRegisterInputTextView.setTag("step2_second");
					mRegisterInputTextView.setText(R.string.registerfirst_inputfield_passwordagain);
					mRegisterInputEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
					mRegisterInputEditText.setHint(R.string.registerfirst_inputfield_passwordagain);
					showRegisterInputField();
				}
			}
		});
	}

	private void initStep1ButtonBeforeVerified() {
		mStep1Button.setText(null);
		String line1 = getString(R.string.registerfirst_unreg_step1_line1);
		String line2 = getString(R.string.registerfirst_unreg_step1_line2);
		SpannableString spanText = ViewsUtil.getRegisterButtonSpannableString(line1, line2);
		mStep1Button.append(spanText);
	}

	private void initStep1ButtonAfterVerified(String userName) {
		mStep1Button.setText(null);
		String line1 = getString(R.string.registerfirst_reg_step1_line1);
		String line2 = getString(R.string.registerfirst_reg_step1_line2);
		SpannableString spanText = ViewsUtil.getRegisterButtonSpannableString(line1, line2 + userName);
		mStep1Button.append(spanText);
		showNextRegisterView();
	}

	private void initStep2ButtonBeforeVerified() {
		String line1 = getString(R.string.registerfirst_unreg_step2_line1);
		String line2 = getString(R.string.registerfirst_unreg_step2_line2);
		SpannableString spanText = ViewsUtil.getRegisterButtonSpannableString(line1, line2);
		mStep2Button.append(spanText);
	}

	private void initStep2ButtonAfterVerified() {
		mStep2Button.setText(null);
		String line1 = getString(R.string.registerfirst_reg_step2_line1);
		String line2 = getString(R.string.registerfirst_reg_step2_line2);
		SpannableString spanText = ViewsUtil.getRegisterButtonSpannableString(line1, line2);
		mStep2Button.append(spanText);
		showNextRegisterView();
	}

	private void initStep3ButtonBeforeVerified() {
		String line1 = getString(R.string.registerfirst_unreg_step3_line1);
		String line2 = getString(R.string.registerfirst_unreg_step3_line2);
		SpannableString spanText = ViewsUtil.getRegisterButtonSpannableString(line1, line2);
		mStep3Button.append(spanText);
	}

	private void initStep3ButtonAfterVerified(String nickname) {
		mStep3Button.setText(null);
		String line1 = getString(R.string.registerfirst_reg_step3_line1);
		String line2 = getString(R.string.registerfirst_reg_step3_line2);
		SpannableString spanText = ViewsUtil.getRegisterButtonSpannableString(line1, line2 + nickname);
		mStep3Button.append(spanText);
		showNextRegisterView();
	}

	protected void handleRegisterInputFieldOkButtenEvent() {
		String step = (String) mRegisterInputTextView.getTag();
		if ("step1".equals(step)) {
			handleStep1RegisterInputFieldOkButtonEvent();
		} else if ("step2_first".equals(step)) {
			handleStep2FirstInputOkButtonEvent();
		} else if ("step2_second".equals(step)) {
			handleStep2SecondInputOkButtonEvent();
		} else if ("step3".equals(step)) {
			handleStep3IRegisterInputFieldOkButtonEvent();
		}
	}

	private void handleStep1RegisterInputFieldOkButtonEvent() {
		String userName = mRegisterInputEditText.getText().toString();
		if (userName == null || userName.length() < 5) {
			ViewsUtil.showErrorTip(this, R.string.registertip_input_tooshort);
			return;
		}
		if (userName.length() > 30) {
			ViewsUtil.showErrorTip(this, R.string.registertip_input_toolong);
			return;
		}
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		try {
			jsonData.put(Constant.PARAM_ACCOUNT, userName);
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_ISUSEREXIST, jsonData);
		} catch (Exception e) {
			jsonResponse.setStatus(Status.ERR);
			e.printStackTrace();
		}
		if (jsonResponse.getStatus() == Status.ERR) {
			ViewsUtil.showErrorTip(this, R.string.global_error_networkerr);
			return;
		}
		JSONObject data = jsonResponse.getData();
		int status = -1;
		try {
			status = data.getInt(Constant.RESP_STATUS);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (status == Constant.RESP_STATUS_REGISTER_USERNAME_EXIST) {
			ViewsUtil.showErrorTip(this, R.string.registertip_username_existed);
			return;
		}
		ViewsUtil.showErrorTip(this, R.string.registertip_username_verified);
		mUserName = userName;
		initStep1ButtonAfterVerified(mUserName);
		hideRegisterInputField();

	}

	private void handleStep2FirstInputOkButtonEvent() {
		String password = mRegisterInputEditText.getText().toString();
		if (password == null || password.length() < 5) {
			ViewsUtil.showErrorTip(this, R.string.registertip_input_tooshort);
			return;
		}
		if (password.length() > 30) {
			ViewsUtil.showErrorTip(this, R.string.registertip_input_toolong);
			return;
		}
		mPasswordFirst = password;
		hideRegisterInputField();
	}

	private void handleStep2SecondInputOkButtonEvent() {
		String password = mRegisterInputEditText.getText().toString();
		if (!password.equals(mPasswordFirst)) {
			ViewsUtil.showErrorTip(this, R.string.registertip_password_unequally);
			return;
		}
		ViewsUtil.showErrorTip(this, R.string.registertip_password_verified);
		mPasswordSecond = password;
		initStep2ButtonAfterVerified();
		hideRegisterInputField();

	}

	private void handleStep3IRegisterInputFieldOkButtonEvent() {
		String nickname = mRegisterInputEditText.getText().toString();
		if (nickname == null || nickname.length() < 4) {
			ViewsUtil.showErrorTip(this, R.string.registertip_nickname_tooshort);
			return;
		}
		if (nickname.length() > 26) {
			ViewsUtil.showErrorTip(this, R.string.registertip_input_toolong);
			return;
		}
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		try {
			jsonData.put(Constant.PARAM_NICKNAME, nickname);
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_ISNICKNAMEUSED, jsonData);
		} catch (Exception e) {
			jsonResponse.setStatus(Status.ERR);
			e.printStackTrace();
		}
		if (jsonResponse.getStatus() == Status.ERR) {
			ViewsUtil.showErrorTip(this, R.string.global_error_networkerr);
			return;
		}
		JSONObject data = jsonResponse.getData();
		int status = -1;
		try {
			status = data.getInt(Constant.RESP_STATUS);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (status == Constant.RESP_STATUS_REGISTER_NICKNAME_USED) {
			ViewsUtil.showErrorTip(this, R.string.registertip_nickname_existed);
			return;
		}
		ViewsUtil.showErrorTip(this, R.string.registertip_nickname_verified);
		mNickname = nickname;
		initStep3ButtonAfterVerified(mNickname);
		hideRegisterInputField();
	}

	private void showRegisterInputField() {
		mRegisterInputField.startAnimation(mAnimIn);
		mRegisterInputField.setVisibility(View.VISIBLE);
		mRegisterInputEditText.requestFocus();
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}

	private void hideRegisterInputField() {
		mRegisterInputEditText.setText("");
		mRegisterInputEditText.setInputType(InputType.TYPE_NULL);
		mRegisterInputEditText.clearFocus();
		mRegisterInputField.startAnimation(mAnimOut);
		mRegisterInputField.setVisibility(View.GONE);
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}

	private void showNextRegisterView() {
		if (mUserName != null && mPasswordSecond != null && mNickname != null) {
			Button nextButton = (Button) findViewById(R.id.gonext_button);
			nextButton.setVisibility(View.VISIBLE);
		}
	}

	public void goBackButton_OnClick(View v) {
		mUserName = null;
		mPasswordFirst = mPasswordSecond = null;
		mNickname = null;
		NavUtils.navigateUpFromSameTask(this);
	}

	public void goNextButton_OnClick(View v) {
//		if(mUserName== null || mPasswordFirst==null || mNickname ==null){
//			Toast.makeText(RegisterFirstViewActivity.this, getString(R.string.registerfirst_unset), Toast.LENGTH_LONG).show();
//			return ;
//		}
		Intent intent = new Intent(this, RegisterSecondViewActivity.class);
		HashMap<String, String> registerFirstViewData = new HashMap<String, String>();
		registerFirstViewData.put(Constant.REGISTER_DATA_USERNAME, mUserName);
		registerFirstViewData.put(Constant.REGISTER_DATA_PASSWORD, mPasswordSecond);
		registerFirstViewData.put(Constant.REGISTER_DATA_NICKNAME, mNickname);
		intent.putExtra(Constant.REGISTER_DATA, registerFirstViewData);
		startActivity(intent);
		
	}

	public void registerStep1Button_OnClick(View v) {
		mRegisterInputTextView.setTag("step1");
		mRegisterInputTextView.setText(R.string.registerfirst_inputfield_username);
		mRegisterInputEditText.setInputType(InputType.TYPE_CLASS_TEXT);
		mRegisterInputEditText.setHint(R.string.registerfirst_inputfieldtip_username);
		if (mUserName != null) {
			mRegisterInputEditText.setText(mUserName);
		}
		showRegisterInputField();
	}

	public void registerStep2Button_OnClick(View v) {
		mRegisterInputTextView.setTag("step2_first");
		mRegisterInputTextView.setText(R.string.registerfirst_inputfield_passwordonce);
		mRegisterInputEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
		mRegisterInputEditText.setHint(R.string.registerfirst_inputfield_passwordonce);
		showRegisterInputField();

	}

	public void registerStep3Button_OnClick(View v) {
		mRegisterInputTextView.setTag("step3");
		mRegisterInputTextView.setText(R.string.registerfirst_inputfield_nickname);
		mRegisterInputEditText.setInputType(InputType.TYPE_CLASS_TEXT);
		mRegisterInputEditText.setHint(R.string.registerfirst_inputfield_nickname);
		if (mNickname != null) {
			mRegisterInputEditText.setText(mNickname);
		}
		showRegisterInputField();

	}

}
